package com.yuanbuluo.sendsms

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.IBinder
import android.telephony.SmsManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import redis.clients.jedis.JedisPool
import redis.clients.jedis.JedisPoolConfig

class SmsService : Service() {

    private val REDIS_HOST = "139.224.70.120"
    private val REDIS_PORT = 30789
    private val REDIS_PASS = "pXk8LYoytNncCdry"
    private val REDIS_QUEUE = "sms_queue"
    private val SENT_SMS_QUEUE = "sent_sms_queue"  // 发送短信反馈队列

    private lateinit var jedisPool: JedisPool
    private val serviceScope = CoroutineScope(Dispatchers.IO)

    override fun onCreate() {
        super.onCreate()

        // 尝试通过反射禁用 Commons Pool2 的 JMX 注册
        val poolConfig = JedisPoolConfig()
        try {
            val method = poolConfig.javaClass.getMethod("setJmxEnabled", Boolean::class.javaPrimitiveType)
            method.invoke(poolConfig, false)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        // 初始化 Jedis 连接池
        jedisPool = JedisPool(poolConfig, REDIS_HOST, REDIS_PORT, 2000, REDIS_PASS)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForegroundService()
        startRedisTask()
        return START_STICKY
    }

    private fun startForegroundService() {
        val channelId = "sms_service_channel"
        val channelName = "短信服务"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(
                channelId,
                channelName,
                NotificationManager.IMPORTANCE_LOW
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(notificationChannel)
        }
        val notification = Notification.Builder(this, channelId)
            .setContentTitle("短信服务运行中")
            .setContentText("正在从队列中读取任务并发送短信")
            .setSmallIcon(R.mipmap.ic_launcher)
            .build()
        startForeground(1, notification)
    }

    private fun startRedisTask() {
        serviceScope.launch {
            while (true) {
                try {
                    jedisPool.resource.use { jedis ->
                        while (true) {
                            // 使用阻塞式 API blpop 等待最多 5 秒
                            val result = jedis.blpop(5, REDIS_QUEUE)
                            if (result != null && result.size >= 2) {
                                val smsData = result[1]
                                try {
                                    val jsonObject = JSONObject(smsData)
                                    val phone = jsonObject.getString("phone")
                                    val expressNum = jsonObject.getString("express_number")
                                    val content = jsonObject.getString("content")
                                    sendSmsDirect(phone, content, expressNum)
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                    println("短信发送失败：$smsData，错误：${e.message}")
                                }
                            }
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    println("Redis 连接或操作错误: ${e.message}")
                    // 出现异常时暂停一段时间，再尝试重连
                    delay(3000)
                }
            }
        }
    }

    private fun sendSmsDirect(phoneNumber: String, message: String, expressNum: String) {
        try {
            val smsManager = SmsManager.getDefault()
            val messageParts = smsManager.divideMessage(message)
            smsManager.sendMultipartTextMessage(phoneNumber, null, messageParts, null, null)

            // 将已发送的短信写入系统短信数据库
            val values = ContentValues().apply {
                put("address", phoneNumber)
                put("body", message)
                put("type", 2) // 2 表示已发送的短信
                put("date", System.currentTimeMillis())
            }
            contentResolver.insert(Uri.parse("content://sms/sent"), values)

            println("短信发送成功: $phoneNumber")
            sendFeedbackToRedis(phoneNumber, expressNum)
        } catch (e: Exception) {
            e.printStackTrace()
            println("短信发送失败: ${e.message}")
        }
    }

    private fun sendFeedbackToRedis(phoneNumber: String, trackingNumber: String) {
        try {
            val feedback = JSONObject().apply {
                put("phone", phoneNumber)
                put("trackingNumber", trackingNumber)
                put("status", "sent")
            }
            jedisPool.resource.use { jedis ->
                jedis.lpush(SENT_SMS_QUEUE, feedback.toString())
            }
            println("发送反馈已推送到 Redis 队列 $SENT_SMS_QUEUE")
        } catch (e: Exception) {
            e.printStackTrace()
            println("反馈推送到 Redis 失败: ${e.message}")
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null // 本服务不支持绑定
    }

    override fun onDestroy() {
        super.onDestroy()
        // 服务销毁时关闭连接池，释放资源
        jedisPool.close()
    }
}
